<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Category;
use App\Models\Category as ModelsCategory;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class CategoryController extends AdminController
{
    /**
     * Make a grid builder.
     * 专家库 期刊库
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Category(), function (Grid $grid) {
            $grid->column('id')->sortable();

            $grid->column('title')->tree();

            $grid->column('img')->image();
            $grid->column('status', '状态')->switch();
            // $grid->model()->orderBy('sort','asc');
            $grid->model()->where('is_del', 0);
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
                $filter->like('title');
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Category(), function (Show $show) {
            $show->field('id');
            $show->img()->image();
            $show->field('title');
            $show->parent_id()->as(function ($id) {
                return ModelsCategory::find($id)->title ?? '暂无';
            });
            // $show->field('is_del');
            $show->field('sort');
            $show->field('create_time')->as(function ($create_time) {
                return date('Y-m-d H:i:s', $create_time);
            });
            $show->field('update_time')->as(function ($update_time) {
                return date('Y-m-d H:i:s', $update_time);
            });
            // $show->field('created_at');
            // $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Category(), function (Form $form) {
            $form->display('id');
            $form->image('img')->autoUpload()->move('medical/category/image/' . date('Y/m'));
            $form->select('parent_id', trans('admin.parent_id'))
                ->options(ModelsCategory::selectOptions())
                ->saving(function ($v) {
                    return (int) $v;
                })->default(0)->required();
            $form->text('title')->required();
            $form->text('sort');
            $form->hidden('status')
            // ->customFormat(function ($v) {
            //     return $v == 1 ? 1 : 0;
            // })
            ->saving(function ($v) {
                return $v;
            });
        });
    }
}
